package io.renren.modules.biz.tongtong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.biz.tongtong.TtlockHttp;
import io.renren.modules.biz.tongtong.dao.LockDao;
import io.renren.modules.biz.tongtong.dto.LockDTO;
import io.renren.modules.biz.tongtong.entity.LockEntity;
import io.renren.modules.biz.tongtong.service.LockService;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 锁子表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-01-06
 */
@Service
public class LockServiceImpl extends CrudServiceImpl<LockDao, LockEntity, LockDTO> implements LockService {

    @Resource
    private TtlockHttp ttlockHttp;

    @Override
    public QueryWrapper<LockEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<LockEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }


    /**
     * 根据锁id查询数据
     * @param lockId
     * @return
     */
    @Override
    public LockEntity getBylockId(int lockId) {
        QueryWrapper<LockEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("lock_id",lockId);
        LockEntity lockEntity = baseDao.selectOne(wrapper);
        return lockEntity;
    }

    /**
     * 更新锁列表
     */
    @Override
    public void updateLock() {

        // 调用接口获取云上锁列表（分页）
        int pageNo = 1;
        int pageSize = 100;
        // 调用方法保存
        updateData(pageNo,pageSize);

    }

    /**
     * 循环多次调用接口保存至表中。。。直至所有数据全部保存
     * @param pageNo
     * @param pageSize
     */
    public void updateData(int pageNo,int pageSize) {
        Map<String,Object> map = ttlockHttp.getLockList(pageNo,pageSize);
        if (map !=null) {
            List<LockEntity> list = (List<LockEntity>) map.get("list");
            list.stream().forEach(lockEntity -> {
                LockEntity lockEntity1 = this.getBylockId(lockEntity.getLockId());
                if (lockEntity1 == null) {
                    this.insert(lockEntity);
                }
            });
            int total = Integer.parseInt(map.get("total").toString());
            if (total > pageNo*pageSize) {
                pageNo+=1;
                updateData(pageNo,pageSize);
            }
        }
    }

}